/*
 *  @Title PojoMapper.java
 *  @Package： com.phoenix.base.util
 *  Copyright (c) 2017 by 江苏深南互联网金融信息服务有限公司  All right reserved
 */
package com.phoenix.core.util;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.StringWriter;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType;

/**
 *  @ClassName PojoMapper
 *  @Description 数据格式与对象间的转换工具类
 *  @author liuwenbin
 *  @version 1.0
 *  @date 2017年7月17日
 */
public class PojoMapper {


	private static ObjectMapper m = new ObjectMapper();
	private static JsonFactory jf = new JsonFactory();

	/**
	 * 将json字符串转换为对象
	 * 
	 * @param jsonAsString
	 * @param pojoClass
	 * @return T
	 */
	public static <T> Object fromJson(String jsonAsString, Class<T> pojoClass) {
		try {
			return m.readValue(jsonAsString, pojoClass);
		} catch (Exception e) {
		}
		return null;
	}

	/**
	 * 将json字符串转换为对象
	 * 
	 * @param jsonAsString
	 * @param JavaType
	 * @return T
	 */
	public static <T> Object fromJson(String jsonAsString, JavaType javaType) {
		try {
			return m.readValue(jsonAsString, javaType);
		} catch (Exception e) {
		}
		return null;
	}

	public static <T> Object fromJson(FileReader fr, Class<T> pojoClass) {
		try {
			return m.readValue(fr, pojoClass);
		} catch (Exception e) {
		}
		return null;
	}

	/**
	 * 转换对象位json 字符串
	 * 
	 * 并换行输出
	 * 
	 * @param pojo
	 * @param prettyPrint
	 *            是否换行输出
	 * @return String
	 */
	public static String toJson(Object pojo, boolean prettyPrint) {
		StringWriter sw = new StringWriter();
		try {
			JsonGenerator jg = jf.createJsonGenerator(sw);
			if (prettyPrint) {
				jg.useDefaultPrettyPrinter();
			}
			m.writeValue(jg, pojo);
		} catch (Exception e) {
		}
		return sw.toString();
	}

	/**
	 * 转换对象位json 字符串
	 * 
	 * @param pojo
	 * @return String
	 */
	public static String toJson(Object pojo) {
		StringWriter sw = new StringWriter();
		try {
			JsonGenerator jg = jf.createJsonGenerator(sw);
			m.writeValue(jg, pojo);
		} catch (Exception e) {
		}
		return sw.toString();
	}

	public static void toJson(Object pojo, FileWriter fw, boolean prettyPrint) {
		try {
			JsonGenerator jg = jf.createJsonGenerator(fw);
			if (prettyPrint) {
				jg.useDefaultPrettyPrinter();
			}
			m.writeValue(jg, pojo);
		} catch (Exception e) {
		}
	}
}
